package com.infotel.chat;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.Timer;

public class Client {
    static JFrame fenetre;
    static JPanel panneauSaisie = new JPanel();
    static JMenuBar barreMenu = new JMenuBar();
    static JMenu menuFichier = new JMenu("Fichier");
    static JMenuItem itemChangerUtilisateur = new JMenuItem(
            "Changer d'utilisateur");
    static JMenuItem itemListe = new JMenuItem("Liste des messages");
    static JMenuItem itemQuitter = new JMenuItem("Quitter");
    static JEditorPane zoneAffichage;

    static JTextField champSaisie;
    
    static Socket client;
    static InputStream fluxLecture;
    static OutputStream fluxEcriture;
    static BufferedReader br;
    static BufferedWriter bw;
    static boolean fin;
    
    static Users user;

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {

            user = new Users("plop");
            client = new Socket("192.168.40.226", 10000);
            fluxLecture = client.getInputStream();
            fluxEcriture = client.getOutputStream();

            br = new BufferedReader(new InputStreamReader(fluxLecture, "UTF-8"));
            bw = new BufferedWriter(new OutputStreamWriter(fluxEcriture,
                    "UTF-8"));

            // SimpleDateFormat sdf = new SimpleDateFormat(
            // "yyyy-MM-dd'T'HH:mm:ss.SSS");
            fenetre = new JFrame();

            zoneAffichage = new JEditorPane("text/html", "");
            zoneAffichage.setEditable(false);
            zoneAffichage.setAutoscrolls(true);

            champSaisie = new JTextField();
            JButton boutonSaisie = new JButton("OK");
            
            Timer timer = new Timer(500,new ClientTimer());
            
            boutonSaisie.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    try {
                        String message = champSaisie.getText();
                        bw.write("ENVOIE MESSAGE\n"+user.getId()+"\n" + message + "\n");
                        bw.flush();
                        br.readLine();
                        champSaisie.setText("");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });
            champSaisie.addKeyListener(new KeyListener() {

                @Override
                public void keyTyped(KeyEvent e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void keyReleased(KeyEvent e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void keyPressed(KeyEvent e) {
                    switch (e.getKeyCode()) {
                    case KeyEvent.VK_ENTER:
                        try {
                            String message = champSaisie.getText();
                            bw.write("ENVOIE MESSAGE\n"+user.getId()+"\n" + message + "\n");
                            bw.flush();
                            br.readLine();
                            champSaisie.setText("");
                        } catch (IOException ex) {
                            // TODO Auto-generated catch block
                            ex.printStackTrace();
                        }
                        break;
                    }

                }
            });
            panneauSaisie = new JPanel();
            panneauSaisie.setLayout(new BorderLayout());
            panneauSaisie.add(champSaisie, BorderLayout.CENTER);
            panneauSaisie.add(boutonSaisie, BorderLayout.EAST);

            fenetre.setLayout(new BorderLayout());
            fenetre.add(panneauSaisie, BorderLayout.SOUTH);
            
            JScrollPane scrollPane = new JScrollPane(zoneAffichage);
            fenetre.add(scrollPane, BorderLayout.CENTER);

            barreMenu = new JMenuBar();
            menuFichier = new JMenu("Fichier");
            itemChangerUtilisateur = new JMenuItem("Changer d'utilisateur");
            itemListe = new JMenuItem("Liste des messages");
            itemQuitter = new JMenuItem("Quitter");

            menuFichier.add(itemChangerUtilisateur);
            menuFichier.add(itemListe);
            menuFichier.add(itemQuitter);
            barreMenu.add(menuFichier);
            fenetre.setJMenuBar(barreMenu);

            itemListe.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    try {
                        bw.write("LISTE MESSAGES\n");
                        bw.flush();
                        String line = "";
                        StringBuilder sb = new StringBuilder();
                        do {
                            line = br.readLine();
                            sb.append(line);
                        } while (!line.equals("</chat>")
                                && !line.equals("<chat/>"));
                        zoneAffichage.setText(Chat
                                .getTexteMessages(new StringReader(sb
                                        .toString())));

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });
            
            itemQuitter.addActionListener(new ActionListener() {
                
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    fin=true;
                    try {
                        bw.write("FIN\n");
                        bw.flush();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.exit(0);
                }
            });
            
            itemChangerUtilisateur.addActionListener(new ActionListener() {
                
                @Override
                public void actionPerformed(ActionEvent e) {
                    SaisieUser saisie = new  SaisieUser();
                    int reponse = JOptionPane.showConfirmDialog(null, saisie,"Saisie utilisateur", JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
                    if(reponse==JOptionPane.OK_OPTION){
                       user =new Users(saisie.getTfUsername().getText(),saisie.getTfEmail().getText(),saisie.getTfGenre().getText()); 
                    }
                }
            });
            fenetre.pack();
            fenetre.setMinimumSize(new Dimension(300, 300));
            fenetre.setVisible(true);
            timer.start();
            fin = false;
            while (!fin) {

            }

            br.close();
            bw.close();
            client.close();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    public static JFrame getFenetre() {
        return fenetre;
    }


    public static void setFenetre(JFrame fenetre) {
        Client.fenetre = fenetre;
    }


    public static JPanel getPanneauSaisie() {
        return panneauSaisie;
    }


    public static void setPanneauSaisie(JPanel panneauSaisie) {
        Client.panneauSaisie = panneauSaisie;
    }


    public static JMenuBar getBarreMenu() {
        return barreMenu;
    }


    public static void setBarreMenu(JMenuBar barreMenu) {
        Client.barreMenu = barreMenu;
    }


    public static JMenu getMenuFichier() {
        return menuFichier;
    }


    public static void setMenuFichier(JMenu menuFichier) {
        Client.menuFichier = menuFichier;
    }


    public static JMenuItem getItemChangerUtilisateur() {
        return itemChangerUtilisateur;
    }


    public static void setItemChangerUtilisateur(JMenuItem itemChangerUtilisateur) {
        Client.itemChangerUtilisateur = itemChangerUtilisateur;
    }


    public static JMenuItem getItemListe() {
        return itemListe;
    }


    public static void setItemListe(JMenuItem itemListe) {
        Client.itemListe = itemListe;
    }


    public static JMenuItem getItemQuitter() {
        return itemQuitter;
    }


    public static void setItemQuitter(JMenuItem itemQuitter) {
        Client.itemQuitter = itemQuitter;
    }


    public static JEditorPane getZoneAffichage() {
        return zoneAffichage;
    }


    public static void setZoneAffichage(JEditorPane zoneAffichage) {
        Client.zoneAffichage = zoneAffichage;
    }


    public static JTextField getChampSaisie() {
        return champSaisie;
    }


    public static void setChampSaisie(JTextField champSaisie) {
        Client.champSaisie = champSaisie;
    }


    public static Socket getClient() {
        return client;
    }


    public static void setClient(Socket client) {
        Client.client = client;
    }


    public static InputStream getFluxLecture() {
        return fluxLecture;
    }


    public static void setFluxLecture(InputStream fluxLecture) {
        Client.fluxLecture = fluxLecture;
    }


    public static OutputStream getFluxEcriture() {
        return fluxEcriture;
    }


    public static void setFluxEcriture(OutputStream fluxEcriture) {
        Client.fluxEcriture = fluxEcriture;
    }


    public static BufferedReader getBr() {
        return br;
    }


    public static void setBr(BufferedReader br) {
        Client.br = br;
    }


    public static BufferedWriter getBw() {
        return bw;
    }


    public static void setBw(BufferedWriter bw) {
        Client.bw = bw;
    }

}
